/**
 * 给你一个链表，删除链表的倒数第 n 个结点，并且返回链表的头结点。
 */
public class exercise02 {
    public ListNode removeNthFromEnd(ListNode head, int n) {
        ListNode cur = head;
        if(head == null || n < 1){
            return null;
        }

        ListNode fast = head;// 快指针先走
        ListNode slow = head;// 慢指针随后
        while (n > 0){
            if(fast == null){
                System.out.println("请输入正确的位置！");
                return null;
            }
            fast = fast.next;
            n--;
        }
        // 找到倒数第k个节点
        while (fast != null){
            fast = fast.next;
            slow = slow.next;
        }
        if(slow == cur){
            return head.next;
        }
        while(cur.next != slow){
            cur = cur.next;
        }
        if(slow.next == null){
            cur.next = null;
        }else{
            cur.next = slow.next;
        }
        return head;
    }
}